
Ext.define('FrontSuite.shared.view.AppToolbar', {
    id:           'fs-apptoolbar',
    extend:       'Ext.toolbar.Toolbar',  // defines the superclass. results in class inheritance.
    alias:        'widget.apptoolbar',    // creates an xtype: 'apptoolbar'
    enableOverflow: true,    // enables a toolbar to overflow if it has too many tools to fit in the width provided
    // resizeable: true,
    // resizeHandles: 'all',

    langData:      null,
    langStore:     null,
    langSelect:    null,
    loginButton:   null,
    helpMenu:      null,
    settingsMenu:  null,
    loginBox:      null,
    usernameField: null,
    passwordField: null,
    registerLink:  null,
    forgotPasswordLink:     null,
    remainLoggedInCheckbox: null,

    constructor: function(id) {
        if (id) {
            this.id = id;
        }
        this._initOnce();
        this._initInstance();
        this.items = [
            // { xtype: 'label', text: 'Home' },
            // '-',
            // { xtype: 'label', text: 'Group:' },
            // '-',
            // { xtype: 'label', text: 'Location:' },
            // '-',
            // settingsMenu,
            // '-',
            // { xtype: 'button', text:  'Logout' },
            {
                xtype: 'component',
                html: '&nbsp;&nbsp;&nbsp;<img src="resources/images/logo_38x44.png" width="35" height="40" style="border:0; padding:0; margin:0" /><span style="font-size: 28px; font-style: italic; font-weight: bold; color: #2e4e74; vertical-align: 8px;">&nbsp;dbfoundry</span>',
                style: 'border:0; padding:0; margin:0'
            },
            '->',
            this.loginBox
        ];
        this.superclass.constructor.call(this, id);
        return(this);
    },

    _initOnce: function () {
        // Define the model for a Language
        Ext.regModel('Language', {
            fields: [
                {type: 'string', name: 'lang'},
                {type: 'string', name: 'text'},
                {type: 'string', name: 'icon'}
            ]
        });
    },

    _initInstance: function () {

        var sharedRoot = FrontSuite.options.shared_root;

        this.langData = [
            { lang: "en-US", text: "English (US)", icon: sharedRoot+"/resources/images/flags/us.png" },
            { lang: "en-GB", text: "English (UK)", icon: sharedRoot+"/resources/images/flags/gb.png" },
            { lang: "fr",    text: "Français",     icon: sharedRoot+"/resources/images/flags/fr.png" },
            { lang: "es",    text: "Español",      icon: sharedRoot+"/resources/images/flags/es.png" },
            { lang: "de",    text: "Deutsch",      icon: sharedRoot+"/resources/images/flags/de.png" },
        ];

        // The data store holding the states
        this.langStore = Ext.create('Ext.data.Store', {
            model: 'Language',
            data: this.langData
        });

        // Create the combo box for selecting the Language
        this.langSelect = Ext.create('Ext.Button', {
            id   : 'fs-lang',
            name : 'fs-lang',
            icon : sharedRoot+'/resources/images/flags/us.png',
            text : 'English (US)',
            menu : this.langData
        });

        this.sessionDuration = Ext.create('Ext.data.Store', {
            fields: ['hours', 'name'],
            data : [
                {'hours':1,   'name':  '1 Hour'},
                {'hours':2,   'name':  '2 Hours'},
                {'hours':4,   'name':  '4 Hours'},
                {'hours':8,   'name':  '8 Hours'},
                {'hours':12,  'name': '12 Hours'},
                {'hours':24,  'name': '24 Hours'},
                {'hours':48,  'name':  '2 Days'},
                {'hours':120, 'name':  '5 Days'},
                {'hours':168, 'name':  '7 Days'},
                {'hours':336, 'name': '14 Days'},
                {'hours':720, 'name': '30 Days'}
            ]
        });

        this.sessionDurationSelect = Ext.create('Ext.form.ComboBox', {
            id: 'fs-duration',
            // fieldLabel: 'Stay Logged In',
            // labelAlign: 'right',
            labelWidth: 85,
            hideLabel: true,
            store: this.sessionDuration,
            // inputType: 'select',
            queryMode: 'local',
            displayField: 'name',
            valueField: 'hours',
            allowBlank: false,
            editable: false,
            forceSelection: true,
            multiselect: false,
            style: 'margin: 0 0 0 6px;',
            // colspan: 2,
            // size: 8,
            // align: 'left',
            // style: 'margin-bottom: 1px; margin-left: 12px;'
            // tdAttrs: { align: 'left', style: { 'text-align': 'left' } },
            size: 8,
            value: 24
        });

        this.loginButton = Ext.create('Ext.Button', {
            id:    'fs-loginbutton',
            text:  'Login',
            style: 'margin-left: 6px',
            width: 81,
            handler: this._login
        });

        // Create the combo box for selecting the Language
        this.helpMenu = Ext.create('Ext.Button', {
            // id: 'fs-helpMenu',
            // name: 'fs-helpMenu',
            // icon : 'images/misc/gear.png',
            text : 'Help',
            // align: 'right',
            tdAttrs: { align: 'right' },
            menu : [
                'About'
            ]
        });

        // Create the combo box for selecting the Language
        this.settingsMenu = Ext.create('Ext.Button', {
            // id: 'fs-settingsMenu',
            // name: 'fs-settingsMenu',
            // icon : 'images/misc/gear.png',
            text : 'Settings',
            menu : [
            ]
        });

        this.usernameField = Ext.create('Ext.form.TextField', {
            // xtype: 'textfield',
            name: 'fs-u',
            id: 'fs-u',
            style: 'margin-bottom: 0px; margin-left: 6px;',
            fieldLabel: 'Username',
            labelSeparator: ':',
            labelAlign: 'right',
            labelWidth: 60,
            labelPad: 2,
            width: 160
        });

        this.passwordField = Ext.create('Ext.form.TextField', {
            // xtype: 'textfield',
            name: 'fs-p',
            id: 'fs-p',
            inputType: 'password',
            style: 'margin-bottom: 0px; margin-left: 6px;',
            fieldLabel: 'Password',
            labelSeparator: ':',
            labelAlign: 'right',
            labelWidth: 60,
            labelPad: 2,
            width: 160
        });

        this.registerLink = Ext.create('Ext.form.Label', {
            // xtype: 'label',
            id: 'fs-register',
            text: 'Register for a new account?',
            tdAttrs: { style: { 'text-align': 'left' } },
            style: 'margin-bottom: 1px; margin-left: 12px; color: blue; text-decoration:underline;'
        });
        this.registerLink.on('render', function (cmp) { cmp.getEl().on('click', this._registerClicked, this); }, this);

        this.forgotPasswordLink = Ext.create('Ext.form.Label', {
            // xtype: 'label',
            id: 'fs-forgot-password',
            text: 'Forgot your password?',
            tdAttrs: { style: { 'text-align': 'left' } },
            style: 'margin-bottom: 1px; margin-left: 14px; color: blue; text-decoration:underline;'
        });
        this.forgotPasswordLink.on('render', function (cmp) { cmp.getEl().on('click', this._forgotPasswordClicked, this); }, this);

        this.remainLoggedInCheckbox = Ext.create('Ext.form.Checkbox', {
            // xtype: 'checkbox',
            name: 'fs-kli2',
            id: 'fs-kli2',
            style: 'margin-bottom: 1px; margin-left: 6px;',
            hideLabel: true,
            boxLabel: 'Remain logged in',
            boxLabelAlign: 'after',
            width: 120,
            colspan: 2
        });

        this.loginBox = Ext.create('Ext.container.Container', {
            layout: {
                type: 'table',
                columns: 5,
            },
            items: [
                this.langSelect,
                this.usernameField,
                this.passwordField,
                this.loginButton,
                this.helpMenu,
                { xtype: 'label', text: '' },
                this.registerLink,
                this.forgotPasswordLink,
                this.sessionDurationSelect,
                { xtype: 'label', text: 'Login time', style: 'margin: 0 4px 0 4px;' }
                //this.remainLoggedInCheckbox
            ]
        });

        // this.registrationPanel = Ext.create('FrontSuite.shared.view.RegistrationWizard');
        this.registrationPanel = Ext.create('FrontSuite.shared.view.AppRegistrationPanel');
        this.passwordRecoveryPanel = Ext.create('FrontSuite.shared.view.AppPasswordRecoveryPanel');
    },

    _login: function() {
        var sharedRoot    = FrontSuite.options.shared_root;
        var usernameField = Ext.getCmp('fs-u');
        var username      = usernameField.getValue();
        var passwordField = Ext.getCmp('fs-p');
        var password      = passwordField.getValue();
        var durationField = Ext.getCmp('fs-duration');
        var duration      = durationField.getValue();
        passwordField.setValue('');                  // null out the password field. we don't want the browser to offer to save it.
        var clientConnectionToken = FrontSuite.connection.clientConnectionToken;

        // console.log('loginButton.handler(): u=['+username+'] password=['+password+']');

        Ext.Ajax.request({
            url       : sharedRoot+'/ff-auth.php',
            params    : {'op': 'authspec', 'username' : username, 'clientConnectionToken' : clientConnectionToken},
            autoAbort : false,
            method    : 'POST',
            scope     : this,
            success : function(response){
                // console.log(response);
                var authspecResponse  = Ext.JSON.decode(response.responseText);
                var userSalt          = authspecResponse.userSalt;
                var userId            = authspecResponse.userId;
                var algorithm         = authspecResponse.algorithm;
                var algorithmOption   = authspecResponse.algorithmOption;
                var currentDate       = new Date();
                var currentTime       = currentDate.getTime();              // returns milliseconds since 1970-01-01 00:00:00 UTC
                var sessionExpireTime = currentTime + duration*3600*1000;   // expire in the specified number of hours
                var sessionExpireDate = new Date(sessionExpireTime);
                var session_expire_dttm = sessionExpireDate.toISOString();
                session_expire_dttm     = session_expire_dttm.replace(/\.[0-9]+Z$/,'Z');
                var passwordHash      = FrontSuite.makePasswordHash(algorithm, algorithmOption, password, userSalt);
                var auth_token         = FrontSuite.makeAuthToken(passwordHash, session_expire_dttm, clientConnectionToken);
// console.log('-------------------------------');
// console.log('username: ' + username);
// console.log('password: ' + password);
// console.log('duration: ' + duration);
// console.log('currentDttm: ' + currentDate.toISOString());
// console.log('session_expire_dttm: ' + session_expire_dttm);
// console.log('auth_token: ' + auth_token);
                Ext.Ajax.request({
                    url       : sharedRoot+'/ff-auth.php',
                    params    : {'op': 'auth', 'username': username, 'session_expire_dttm': session_expire_dttm, 'auth_token': auth_token},
                    autoAbort : false,
                    method    : 'POST',
                    scope     : this,
                    success : function(response){
                        var authResponse  = Ext.JSON.decode(response.responseText);
                        if (authResponse.success) {
                            FrontSuite.session.username          = username;
                            FrontSuite.session.session_expire_dttm = session_expire_dttm;
                            FrontSuite.session.auth_token         = auth_token;
console.log('OOPS: app/shared/view/AppToolbar.js');
// console.log(FrontSuite.session);
// console.log(Ext.JSON.encode(FrontSuite.session));
                            // Ext.util.Cookies.set(name, value, [expires], [path], [domain], [secure]);
                            Ext.util.Cookies.set('ff-session', Ext.JSON.encode(FrontSuite.session), sessionExpireDate, '/', null, true);
                            Ext.MessageBox.show({
                               title   : 'Login Successful',
                               msg     : 'Login Successful',
                               buttons : Ext.MessageBox.OK
                            });
                        }
                        else {
                            Ext.MessageBox.show({
                               title   : 'Login Failed',
                               msg     : 'Login Failed: Username or Password is incorrect',
                               buttons : Ext.MessageBox.OK
                            });
                        }
                    },
                    failure: function(response, opts) {
                        Ext.MessageBox.show({
                           title   : 'Login Failed',
                           msg     : 'Login Failed: ' + response.status,
                           buttons : Ext.MessageBox.OK
                        });
                    }
                });
            },
            failure: function(response, opts) {
                Ext.MessageBox.show({
                   title   : 'Login Failed',
                   msg     : 'Login Failed: ' + response.status,
                   buttons : Ext.MessageBox.OK
                });
            }
        });
    },
    _registerClicked: function() {
        this.registrationPanel.show();
    },
    _forgotPasswordClicked: function() {
        this.passwordRecoveryPanel.show();
    }
});

